package com.student_exam_system.controller;

import com.alibaba.fastjson.JSON;
import com.student_exam_system.pojo.Question;
import com.student_exam_system.service.QuestionService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fire'ge
 */
@Controller
@RequestMapping(value = "/question")
public class QuestionController {
    private final QuestionService questionService;
    private final Map<String,List<Question>> questionsMap = new HashMap<>();

    public QuestionController(@Qualifier("questionServiceImpl") QuestionService questionService) {
        this.questionService = questionService;
    }

    @PreAuthorize("hasAuthority('student')")
    @RequestMapping(value = "/queryQueData/{paperId}",produces = "application/json;charset=utf-8")
    public String queryQueData(@PathVariable int paperId,HttpServletRequest request) {
        if (!questionsMap.containsKey(paperId+"")){
            List<Question> questions = questionService.queryQuestionsByPaperId(paperId);
            if (!(questions.isEmpty())){
                questionsMap.put(""+paperId,questions);
                request.getSession().setAttribute("paperId",paperId);
            }
        }
        return "forward:/userPaper/addUserPaper";
    }


    @PreAuthorize("hasAuthority('student')")
    @RequestMapping(value = "/showQueData/{paperListId}",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String showQueData(@PathVariable int paperListId, HttpServletRequest request) {
        String paperId = (String) request.getSession().getAttribute("paperId");
        List<Question> questions = questionsMap.get(paperId);
            if (questions.isEmpty()) {
                throw new RuntimeException("你请求的的试卷数据不存在");
            }
        Question question = questions.get(paperListId-1);
            request.getSession().setAttribute("questionId",question.getQuestionId());
        return JSON.toJSONString(question);
    }
    @PreAuthorize("hasAuthority('teacher')")
    @RequestMapping("/addQuestion")
    @ResponseBody
    public int addQuestion(String content, String type, String answer, String score){
        return questionService.addQuestion(content, type, answer, score);
    }
}
